package com.livesource.client.webservices.subversion;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.jsonp.client.JsonpRequestBuilder;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.livesource.client.LiveSourceGlobalVariables;
import com.livesource.client.model.entry.ProjectClass;
import com.livesource.client.model.project.Project;
import com.livesource.client.utilities.ConvertJsonp;
import com.livesource.client.utilities.FileExtensions;

public class RequestSubversionFileContent {

	private static String url = "http://livesourceagile.com:8080/LiveSourceWebServices/GetSubversionClassDocumentService";

	public static void getJsonpRequest(Project project, final String filePath) {

		// String username = GetCookies.getUsername(project.getProjectID());
		String username = null;

		// String password = GetCookies.getPassword(project.getProjectID());
		String password = null;

		JsonpRequestBuilder jsonp = new JsonpRequestBuilder();

		String urlSave = url + "?repositoryURL=" + project.getRepositoryURL()
				+ "&filePath=" + filePath + "&username=" + username
				+ "&password=" + password;

		jsonp.requestObject(urlSave, new AsyncCallback<JavaScriptObject>() {

			public void onFailure(Throwable throwable) {

				System.out.println("Error: " + throwable);
			}

			public void onSuccess(JavaScriptObject feed) {

				JSONObject entry = new JSONObject(feed);

				ProjectClass projectClass = LiveSourceGlobalVariables.projectEntries
						.get(filePath);

				projectClass.setFileContent(ConvertJsonp.convertToString(entry
						.get("fileContent")));

				String fileExtension = FileExtensions
						.getFileExtension(filePath);

				if (FileExtensions.EXTENSION_JAVA.equals(fileExtension)) {

					projectClass = ConvertJsonpToJavaDocumentation.convert(
							projectClass, entry);

				} else if (FileExtensions.EXTENSION_FEATURE
						.equals(fileExtension)) {

					projectClass = ConvertJsonpToFeatureFile.convert(
							projectClass, entry);
				}

				LiveSourceGlobalVariables.projectEntries.put(filePath,
						projectClass);
			}
		});
	}
}
